package com.zj.blessings.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zj.blessings.R;
import com.zj.blessings.db.DBCategory;
import com.zj.blessings.db.DBItem;
import com.zj.blessings.util.ResourceUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CategoryAdapter extends BaseAdapter {
	private List<DBCategory> mCategorys = new ArrayList<DBCategory>();
	private Context mContext;
	private int[] mRes;
	private Map<String, Long> map = new HashMap<String, Long>();
	private Map<String, Long> unReadMap = new HashMap<String, Long>();

	public CategoryAdapter(Context context) {
		this.mContext = context;
		mRes = ResourceUtils.getRes();
	}

	public void setCategoryItems(List<DBCategory> categoryItems) {
		mCategorys.clear();
		if (categoryItems != null) {
			for (DBCategory categoryItem : categoryItems) {
				mCategorys.add(categoryItem);
				long n = DBItem.getDBItemSize(categoryItem.category);
				map.put(categoryItem.category, n);
				long m = DBItem.getDBItemUnReadSize(categoryItem.category);
				unReadMap.put(categoryItem.category, m);
			}
		}
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return mCategorys.size();
	}

	@Override
	public Object getItem(int position) {
		return mCategorys.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder vh = null;
		if (convertView == null) {
			vh = new ViewHolder();
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.category_item, null);
			vh.tip = (TextView) convertView.findViewById(R.id.categoryItemTip);
			vh.image = (ImageView) convertView
					.findViewById(R.id.categoryItemImage);
			vh.category = (TextView) convertView
					.findViewById(R.id.categoryItemCategory);
			vh.count = (TextView) convertView
					.findViewById(R.id.categoryItemCategoryCount);
			convertView.setTag(vh);
		} else {
			vh = (ViewHolder) convertView.getTag();
		}
		if (mRes != null && mRes.length > 0) {
			vh.image.setBackgroundResource(mRes[position % mRes.length]);
		}
		vh.category.setText(mCategorys.get(position).category);
		long count = map.get(mCategorys.get(position).category);
		vh.count.setText("(" + count + ")");
		long unReadNum = unReadMap.get(mCategorys.get(position).category);
		if (unReadNum > 0) {
			vh.tip.setVisibility(View.VISIBLE);
			vh.tip.setText(String.valueOf(unReadNum));
		} else {
			vh.tip.setVisibility(View.GONE);
		}

		return convertView;
	}

	class ViewHolder {
		TextView tip;
		ImageView image;
		TextView category;
		TextView count;
	}
}
